"use client";

import { Card, Space, Spin, Row, Col } from "antd";
import { useEffect, useState } from "react";
import { API_NAME, CATEGORY_BACK_COLOR, MOCK_CATEGORY_LIST } from "../../constant";
import "./index.css";

const PrimaryList = ({ changePrimaryId }) => {
  const [loading, setLoading] = useState(false);
  const [primaryCategoryId, setPrimaryCategoryId] = useState("");
  const [categoryList, setCategoryList] = useState([]);

  const getPrimaryCategoryInfo = async () => {
    setLoading(true);
    try {
      const data = MOCK_CATEGORY_LIST;
      if (data?.length > 0) {
        setPrimaryCategoryId(data[0].id);
        setCategoryList(data);
        changePrimaryId(data[0].id);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getPrimaryCategoryInfo();
  }, []);

  return (
    <Spin spinning={loading}>
      <div className="category-container">
        <Row gutter={[12, 12]}>
          {categoryList.map((item, index) => (
            <Col key={item.id} xs={12} sm={8} md={6} lg={4} xl={4}>
              <Card
                className={`category-card ${item.id === primaryCategoryId ? "active" : ""}`}
                style={{
                  background: `linear-gradient(135deg, ${lightenColor(CATEGORY_BACK_COLOR[index], 20)} 0%, ${CATEGORY_BACK_COLOR[index]} 100%)`,
                }}
                onClick={() => {
                  setPrimaryCategoryId(item.id);
                  changePrimaryId(item.id);
                }}
              >
                <div className="card-content">
                  <div className="category-name">{item.categoryName}</div>
                  <div className="question-count">{item.count}道题</div>
                </div>
              </Card>
            </Col>
          ))}
        </Row>
      </div>
    </Spin>
  );
};

// 辅助函数：颜色变浅
function lightenColor(color, percent) {
  const num = parseInt(color.replace("#", ""), 16);
  const amt = Math.round(2.55 * percent);
  const R = (num >> 16) + amt;
  const G = ((num >> 8) & 0x00ff) + amt;
  const B = (num & 0x0000ff) + amt;
  return `#${(
    0x1000000 +
    (R < 255 ? R : 255) * 0x10000 +
    (G < 255 ? G : 255) * 0x100 +
    (B < 255 ? B : 255)
  )
    .toString(16)
    .slice(1)}`;
}

export default PrimaryList;